package com.vincce.sport.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.core.utils.SimpleStorageClient.StorageResult;
import com.vincce.sport.entity.Bottom;
import com.vincce.sport.entity.ImgStorage;
import com.vincce.sport.mapper.BottomMapper;

@Controller
@RequestMapping("/footer")
public class BottomController extends BaseController{
	@Resource
	private BottomMapper footerMapper;
	
	@RequestMapping("/footerForm")
	public String getFooter(Model model){
		List<Bottom> footerList= footerMapper.queryBottomByParentId(0);
		if(footerList!=null && footerList.size()>0){
			for(int i=0;i<footerList.size();i++){
				Integer p=footerList.get(i).getId();
				footerList.get(i).setFooterList(replace(footerMapper.queryBottomByParentId(p)));
			}
		}else{
			footerList=new ArrayList<Bottom>();
		}
		model.addAttribute("footerL", footerList);
		return "/backstage/footerForm";
	}
	
	@RequestMapping("/addOrUpdate")
	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public String addOrUpdate(Model model,HttpServletRequest request) throws IOException{
		String img="";
		Bottom f=new Bottom();
		Boolean flag = false;
	    Map<String, Object> result = new HashMap<String, Object>();
	    String[]  title=request.getParameterValues("title");
        // 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;     
        StorageResult obj = new StorageResult(200, "");
        
        footerMapper.deleteAll(); 
        for(int i=0;i<title.length;i++){
        	if(i==4 || i==5){
    			f.setImgUrl("");
        		f.setFooterHref("");
        		f.setName(title[i]);
        		f.setParentId(0);
        		Integer fid=footerMapper.insertBottom(f);
        		MultipartFile file = multipartRequest.getFile("file"+i);
    			if (file != null && !file.isEmpty()) {
                    String fileName = file.getOriginalFilename();
                    String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                    if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
                    	img="";
                		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
                		result.put("suc", false);
                    } else {
                        obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
                        if (obj.statusCode == 200) {                       	
                        	String path = obj.info.replaceAll("\\\\", "/");                       	
                    		img=path;                        	
                        }
                    }
                } else{
                    img=request.getParameter("img"+i);
                	if(img!=null && !img.equals("")){
                		                  	
                	}else{
                		img="";
                		result.put("msg","请选择文件!");
                        result.put("suc", false);
                	}                	                	
                }
    			if(fid>0){  
        			Bottom b=new Bottom();
    				b.setImgUrl(img);
            		b.setFooterHref("");
            		b.setName("");
            		b.setParentId(f.getId());
    				footerMapper.insertBottom(b);        			
        		}
    			
    		}else{
    			f.setImgUrl("");
        		f.setFooterHref("");
        		f.setName(title[i]);
        		f.setParentId(0);
        		Integer fid=footerMapper.insertBottom(f);
        		if(fid>0){
        			String[]  titleA=request.getParameterValues("title"+(i+1)); 
        			String[]  urlA=request.getParameterValues("url"+(i+1));
        			Bottom b=new Bottom();
        			for(int j=0;j<titleA.length;j++){
        				b.setImgUrl("");
                		b.setFooterHref(urlA[j]);
                		b.setName(titleA[j]);
                		b.setParentId(f.getId());
        				footerMapper.insertBottom(b);
        			}
        		}
    		}
        }
		
		flag = true;
        result.put("suc", flag);
        return JSON.toJSONString(result);
	}
	
	/**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<Bottom> replace(List<Bottom> imgStorageList){
		if(imgStorageList!=null && imgStorageList.size()>0){
			for(Bottom isl:imgStorageList){
				isl.setImgHref(isl.getImgUrl());
				isl.setImgUrl(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+isl.getImgUrl(), "ori"));				
			}
		}
		return imgStorageList;
	}
}
